<template>
  <div class="p-2">
    <el-dialog v-model="selectDialog.visible.value" :title="selectDialog.title.value" width="80%" append-to-body>
      <el-row :gutter="20">
        <el-col :lg="20" :xs="24">
          <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="mb-[10px]">
              <el-card shadow="hover">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="120">
                  <el-form-item label="供应商代码" prop="supplierCode">
                    <el-input v-model="queryParams.supplierCode" placeholder="请输入名称" clearable />
                  </el-form-item>
                  <el-form-item label="供应商名称" prop="supplierName">
                    <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
          </transition>

          <el-card shadow="hover">
            <template v-if="prop.multiple" #header>
              <el-tag v-for="record in selectList" :key="record.id" closable style="margin: 2px" @close="handleCloseTag(record)">
                {{ record.supplierName }}
              </el-tag>
            </template>

            <vxe-table
              ref="tableRef"
              height="400px"
              border
              show-overflow
              :data="dataList"
              :loading="loading"
              :row-config="{ keyField: 'id', isHover: true }"
              :checkbox-config="{ reserve: true, trigger: 'row', highlight: true, showHeader: prop.multiple }"
              @checkbox-all="handleCheckboxAll"
              @checkbox-change="handleCheckboxChange"
            >
              <vxe-column type="checkbox" width="50" align="center" />
              <vxe-column key="supplierCode" title="供应商代码" align="center" field="supplierCode" />
              <vxe-column key="supplierName" title="公司名称" align="center" field="supplierName" />
              <vxe-column key="contactPerson" title="联系人" align="center" field="contactPerson" />
            </vxe-table>

            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :total="total"
              @pagination="pageList"
            />
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listSupplier } from '@/api/purchase/supplier';
import { SupplierVO, SupplierQuery } from '@/api/purchase/supplier/types';
import { VxeTableInstance } from 'vxe-table';
import useDialog from '@/hooks/useDialog';

interface PropType {
  modelValue?: SupplierVO[] | SupplierVO | undefined;
  multiple?: boolean;
  data?: string | number | (string | number)[];
}

const prop = withDefaults(defineProps<PropType>(), {
  multiple: true,
  modelValue: undefined,
  data: undefined
});
const emit = defineEmits(['update:modelValue', 'confirmCallBack']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dataList = ref<SupplierVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const selectList = ref<SupplierVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const tableRef = ref<VxeTableInstance<SupplierVO>>();

const selectDialog = useDialog({
  title: '供应商选择'
});

const queryParams = ref<SupplierQuery>({
  pageNum: 1,
  pageSize: 10,
  supplierCode: undefined,
  supplierName: undefined,
  params: {}
});

/** 根据名称筛选部门树 */
watchEffect(() => {}, {
  flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
});

const confirm = () => {
  emit('update:modelValue', selectList.value);
  emit('confirmCallBack', selectList.value);
  selectDialog.closeDialog();
};

/** 查询用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSupplier(queryParams.value);
  loading.value = false;
  dataList.value = res.rows;
  total.value = res.total;
};

const pageList = async () => {
  debugger;
  await getList();
  const datas = dataList.value.filter((item) => {
    return selectList.value.some((record) => record.id === item.id);
  });
  await tableRef.value.setCheckboxRow(datas, true);
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = (refresh = true) => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  refresh && handleQuery();
};

const handleCheckboxChange = (checked) => {
  if (!prop.multiple && checked.checked) {
    tableRef.value.setCheckboxRow(selectList.value, false);
    selectList.value = [];
  }
  const row = checked.row;
  if (checked.checked) {
    selectList.value.push(row);
  } else {
    selectList.value = selectList.value.filter((item) => {
      return item.id !== row.id;
    });
  }
};
const handleCheckboxAll = (checked) => {
  const rows = dataList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectList.value.some((item) => item.id === row.id)) {
        selectList.value.push(row);
      }
    });
  } else {
    selectList.value = selectList.value.filter((item) => {
      return !rows.some((row) => row.id === item.id);
    });
  }
};

const handleCloseTag = (record: SupplierVO) => {
  const id = record.id;
  const index = selectList.value.findIndex((item) => item.id === id);
  const rows = selectList.value[index];
  tableRef.value?.setCheckboxRow(rows, false);
  selectList.value.splice(index, 1);
};

const close = () => {
  selectDialog.closeDialog();
};

watch(
  () => selectDialog.visible.value,
  async (newValue: boolean) => {
    if (newValue) {
      await getList(); // 初始化列表数据
    } else {
      tableRef.value.clearCheckboxReserve();
      tableRef.value.clearCheckboxRow();
      resetQuery(false);
      selectList.value = [];
    }
  }
);

defineExpose({
  open: selectDialog.openDialog,
  close: selectDialog.closeDialog
});
</script>

<style lang="scss" scoped></style>
